package com.sg.zhui.visitor.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.core.lib.application.BaseFragment;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.utils.*;
import com.core.lib.utils.geneal.AppModifyImageActivity;
import com.core.lib.utils.geneal.AppModifyImageActivity2;
import com.core.lib.utils.main.ImageUtilBase;
import com.core.lib.utils.main.SdUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.photo.AppPhotoFolderActivity;
import com.sg.zhui.visitor.R;

import java.io.File;

/**
 * Created by wondercupid on 2017/4/4.
 */

//重写该类，替换布局
public class UploadMenuImage_Visitor {
    private static final int RESULT_CAMERA = 10;
    private static final int RESULT_PHOTO = 11;
    private static final int RESULT_CROP = 12;
    private static UploadMenuImage_Visitor mInstance = null;
    private static Activity mActivity = null;
    private static BaseFragment mBaseFragment = null;
    private String mTempFilePath = "";
    private boolean mIsCut = true;
    private boolean mIsPhotoDouble = false;
    private int mMaxSelectPhoto = 9;
    private RelativeLayout mPopupView;
    private View.OnClickListener mPopPhotoClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            int rid = v.getId();
            if (rid == R.id.cameraLayout) {
                UploadMenuImage_Visitor.this.jumpCamera();
            } else if (rid == R.id.photoLayout) {

                UploadMenuImage_Visitor.this.jumpPhoto();
            } else if (rid == R.id.cancelLayout) {
                UploadMenuImage_Visitor.this.dismissPopAddPhoto();
            } else if (rid == R.id.popAllLayout) {
                UploadMenuImage_Visitor.this.dismissPopAddPhoto();
            }

        }
    };

    private UploadMenuImage_Visitor() {
    }

    public static UploadMenuImage_Visitor getInstance(Activity activity) {
        if (mInstance == null) {
            mInstance = new UploadMenuImage_Visitor();
        }

        mActivity = activity;
        mBaseFragment = null;
        return mInstance;
    }

    public static UploadMenuImage_Visitor getInstance(BaseFragment baseFragment) {
        if (mInstance == null) {
            mInstance = new UploadMenuImage_Visitor();
        }

        mBaseFragment = baseFragment;
        mActivity = (BaseFragmentActivity) baseFragment.getActivity();
        return mInstance;
    }

    public void setFilePath(String tempFilePath) {
        this.mTempFilePath = tempFilePath;
    }

    public void setIsCut(boolean isCut) {
        this.mIsCut = isCut;
    }

    public void setIsPhotoDouble(boolean isDouble) {
        this.mIsPhotoDouble = isDouble;
    }

    public void setPhotoDoubleNum(int maxCount) {
        this.mMaxSelectPhoto = maxCount;
    }

    @SuppressLint({"InflateParams"})
    public void showPopAddPhoto() {
        View view = LayoutInflater.from(mActivity).inflate(R.layout.pop_select_photo_new_make, (ViewGroup) null);
        LinearLayout cameraLayout = (LinearLayout) view.findViewById(R.id.cameraLayout);
        LinearLayout photoLayout = (LinearLayout) view.findViewById(R.id.photoLayout);
        LinearLayout cancelLayout = (LinearLayout) view.findViewById(R.id.cancelLayout);
        cameraLayout.setOnClickListener(this.mPopPhotoClickListener);
        photoLayout.setOnClickListener(this.mPopPhotoClickListener);
        cancelLayout.setOnClickListener(this.mPopPhotoClickListener);

        // 设置点击事件
        view.findViewById(R.id.popAllLayout).setOnClickListener(this.mPopPhotoClickListener);
        ;

        // 设置动画
        view.setAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.lib_push_down_up_in));
        mPopupView = (RelativeLayout) view.findViewById(R.id.popOutLayout);
        mPopupView.startAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.lib_push_down_up_out));

        PopUtil.getInstance().showPopWindow(mActivity, (View) null, view, 80, (PopupWindow.OnDismissListener) null, false);
    }

    public void dismissPopAddPhoto() {
        PopUtil.getInstance().dismissPopWindow();
        mInstance = null;
    }

    public static void cropSystemImage(Uri uri, int outputX, int outputY) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("outputFormat", "PNG");
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", true);
        if (mBaseFragment != null) {
            mBaseFragment.startActivityForResult(intent, 12);
        } else {
            mActivity.startActivityForResult(intent, 12);
        }

    }

    public static void customCropImage(Uri uri) {
        Intent intent = new Intent(mActivity, AppModifyImageActivity2.class);
        intent.putExtra("image_uri", uri.toString());
        if (mBaseFragment != null) {
            mBaseFragment.startActivityForResult(intent, 12);
        } else {
            mActivity.startActivityForResult(intent, 12);
        }

    }

    public static boolean cameraIsCanUse() {
        boolean isCanUse = true;
        Camera mCamera = null;

        try {
            mCamera = Camera.open();
            Camera.Parameters e = mCamera.getParameters();
            mCamera.setParameters(e);
        } catch (Exception var4) {
            isCanUse = false;
        }

        if (mCamera != null) {
            try {
                mCamera.release();
            } catch (Exception var3) {
                var3.printStackTrace();
                return isCanUse;
            }
        }

        return isCanUse;
    }

    public void jumpCamera() {
        boolean flag = cameraIsCanUse();
        if (!flag) {
            if (mBaseFragment != null) {
                UIHelper.showToast(mBaseFragment.getActivity(), "照相机权限已禁止,请去应用设置打开");
            } else {
                UIHelper.showToast(mActivity, "照相机权限已禁止,请去应用设置打开");
            }

        } else {
            try {
                Intent e = new Intent("android.media.action.IMAGE_CAPTURE");
                if (!TextUtils.isEmpty(this.mTempFilePath)) {
                    Uri imageUri = Uri.fromFile(new File(this.mTempFilePath));
                    e.putExtra("output", imageUri);
                }

                if (mBaseFragment != null) {
                    mBaseFragment.startActivityForResult(e, 10);
                } else {
                    mActivity.startActivityForResult(e, 10);
                }
            } catch (Exception var3) {
                var3.printStackTrace();
            }

        }

    }

    //进入相册
    public void jumpPhoto() {
        Intent photoIntent;
        if (this.mIsPhotoDouble) {
            photoIntent = new Intent(mActivity, AppPhotoFolderActivity.class);
            photoIntent.putExtra("select_double", true);
            photoIntent.putExtra("jump_class_name", AppModifyImageActivity.class.getName());
            photoIntent.putExtra("max_select_num", this.mMaxSelectPhoto);
            mActivity.startActivity(photoIntent);
        } else {
            photoIntent = new Intent("android.intent.action.PICK", (Uri) null);
            photoIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            if (mBaseFragment != null) {
                mBaseFragment.startActivityForResult(photoIntent, 11);
            } else {
                mActivity.startActivityForResult(photoIntent, 11);
            }
        }

    }

    public void onActivityResult(CallBack callBack, int requestCode, int resultCode, Intent data) {
        if (resultCode == -1) {
            int smallWidth = com.core.lib.utils.DensityUtil.dip2px(mActivity, 200.0F);
            int smallHeight = com.core.lib.utils.DensityUtil.dip2px(mActivity, 200.0F);
            int bigWidth = com.core.lib.utils.DensityUtil.dip2px(mActivity, 1152.0F); //  240.0F 480   750
            int bigHeight = com.core.lib.utils.DensityUtil.dip2px(mActivity, 1920.0F); //  400.0F  800  1080
            if (requestCode == 10) {
                Uri bundle;
                if (this.mIsCut) {
                    this.dowithBitmapUri(this.mTempFilePath, smallWidth, smallHeight);
                    bundle = Uri.fromFile(new File(this.mTempFilePath));
                    customCropImage(bundle);
                } else {
                    this.dowithBitmapUri(this.mTempFilePath, bigWidth, bigHeight);
                    bundle = Uri.fromFile(new File(this.mTempFilePath));
                    this.dismissPopAddPhoto();
                    callBack.callBackSuccess(bundle);
                }
            } else {
                String filePath;
                if (requestCode == 11) {
                    String bundle1 = ImageUtilBase.getImageAbsolutePath(mActivity, data.getData());
                    filePath = SdUtilBase.getTempImagePath(mActivity, String.valueOf(System.currentTimeMillis()));
                    if (TextUtils.isEmpty(bundle1)) {
                        return;
                    }

                    Uri tempFile;
                    if (this.mIsCut) {
                        this.dowithBitmapUri(bundle1, filePath, smallWidth, smallHeight);
                        tempFile = Uri.fromFile(new File(filePath));
                        customCropImage(tempFile);
                    } else {
                        this.dowithBitmapUri(bundle1, filePath, bigWidth, bigHeight);
                        tempFile = Uri.fromFile(new File(filePath));
                        this.dismissPopAddPhoto();
                        callBack.callBackSuccess(tempFile);
                    }
                } else if (requestCode == 12) {
                    Bundle bundle2 = data.getExtras();
                    if (bundle2 != null) {
                        filePath = bundle2.getString("data");
                        if (!TextUtils.isEmpty(this.mTempFilePath)) {
                            File tempFile1 = new File(this.mTempFilePath);
                            if (tempFile1.exists()) {
                                tempFile1.delete();
                            }
                        }

                        this.dismissPopAddPhoto();
                        callBack.callBackSuccess(filePath);
                    }
                }
            }
        }

    }

    private void dowithBitmapUri(String filePath, int width, int height) {
        int degree = ImageUtilBase.readPictureDegree(filePath);
        Bitmap tmepBitmap = ImageUtilBase.getBitmap(filePath, width, height);
        Bitmap bitmap = ImageUtilBase.rotaingImageView(degree, tmepBitmap);
        ImageUtilBase.saveImageToSd(bitmap, filePath);
    }

    private void dowithBitmapUri(String filePath, String outputPath, int width, int height) {
        int degree = ImageUtilBase.readPictureDegree(filePath);
        Bitmap tmepBitmap = ImageUtilBase.getBitmap(filePath, width, height);
        Bitmap bitmap = ImageUtilBase.rotaingImageView(degree, tmepBitmap);
        ImageUtilBase.saveImageToSd(bitmap, outputPath);
    }
}
